package com.chuanyang.driverh.mainmy;


import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chuanyang.driverh.BaseApplication;
import com.chuanyang.driverh.R;
import com.chuanyang.driverh.amap.LocationEntity;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.bean.EditCarTeamData;
import com.chuanyang.driverh.bean.FleetLine;
import com.chuanyang.driverh.bean.LcFleet;
import com.chuanyang.driverh.bean.PathEntity;
import com.chuanyang.driverh.responseresult.DriverInfoData;
import com.chuanyang.driverh.responseresult.LogisticsCompanyData;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.responseresult.UpLoadImageResult;
import com.chuanyang.driverh.utils.ActivityUtil;
import com.chuanyang.driverh.utils.BitmapUtil;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.LogUtils;
import com.chuanyang.driverh.utils.PermissoinUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.eventbus.AddAddrEvent;
import com.chuanyang.driverh.utils.eventbus.SelectCompanyEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;

import java.io.File;
import java.util.ArrayList;

import me.nereo.multi_image_selector.MultiImageSelector;
import okhttp3.Call;


/**
 *
 */
public class EditCarTeamActivity extends BaseTitleActivity {
    private LinearLayout ll_editcar_teamphoto;
    private EditText tv_editcarteam_teamname;
    private TextView tv_editcarteam_companyname;
    private EditText tv_editcarteam_phone;
    private LinearLayout ll_editcarteam_endadd;
    private LinearLayout ll_editcarteam_startadd;
//    private LinearLayout ll_editcarteam_icons;
    private TextView tv_editcarteam_startadd;
    private TextView tv_editcarteam_endadd;
    private ImageView iv_editcarteam_icon1;
    private ImageView iv_editcarteam_icon2;
    private ImageView iv_editcarteam_icon3;
    private TextView tv_editcar_carshipphoto;
    private LinearLayout ll_editeteam_carteam;
    private LinearLayout ll_editeteam_shipteam;
    private TextView submit;


    private boolean isCreateCarTeam = true;//默认要创建车队
    private DriverInfoData driverinfo;
    private EditCarTeamData editCarTeamData;
    private LcFleet lcFleet;
    private ArrayList<FleetLine> fleetLines;
    private FleetLine fleetLine;
    private ArrayList<File> compressfiles;
    private ArrayList<String> fleetImgs;
    private PathEntity endPath;//终止地
    private PathEntity startPath;//起始地

    private int maxNum = 3;
    private ArrayList<String> mSelectPath;
    private static final int REQUEST_IMAGE = 2;
    @Override
    protected int getContentResId() {
        return R.layout.my_act_editcarteam;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        ll_editeteam_carteam = (LinearLayout) findViewById(R.id.ll_editeteam_carteam);
        ll_editeteam_shipteam = (LinearLayout) findViewById(R.id.ll_editeteam_shipteam);
        tv_editcarteam_teamname = (EditText) findViewById(R.id.tv_editcarteam_teamname);//车队队名
        tv_editcar_carshipphoto = (TextView) findViewById(R.id.tv_editcar_carshipphoto);//区别是车队照片还是船队照片
        tv_editcarteam_phone = (EditText) findViewById(R.id.tv_editcarteam_phone);//电话号码
        ll_editcarteam_endadd = (LinearLayout) findViewById(R.id.ll_editcarteam_endadd);//点击获取终点
        ll_editcarteam_startadd = (LinearLayout) findViewById(R.id.ll_editcarteam_startadd);//点击获取起点
//        ll_editcarteam_icons = (LinearLayout) findViewById(ll_editcarteam_icons);//加载图片的父布局
        tv_editcarteam_startadd = (TextView) findViewById(R.id.tv_editcarteam_startadd);//起始点
        tv_editcarteam_endadd = (TextView) findViewById(R.id.tv_editcarteam_endadd);//终点
        tv_editcarteam_companyname = (TextView) findViewById(R.id.tv_editcarteam_companyname);//所属公司
        iv_editcarteam_icon1 = (ImageView) findViewById(R.id.iv_editcarteam_icon1);
        iv_editcarteam_icon2 = (ImageView) findViewById(R.id.iv_editcarteam_icon2);
        iv_editcarteam_icon3 = (ImageView) findViewById(R.id.iv_editcarteam_icon3);
        //提交
        submit = (TextView) findViewById(R.id.tv_act_editcarteam_submit);
        ll_editcar_teamphoto = (LinearLayout) findViewById(R.id.ll_editcar_teamphoto);

    }

    @Override
    protected void initData() {
        compressfiles = new ArrayList();
        fleetImgs = new ArrayList();
        mSelectPath = new ArrayList();
        fleetLine = new FleetLine();
        editCarTeamData = new EditCarTeamData();
        fleetLines = new ArrayList();
        driverinfo = BaseApplication.getInstance().getDriverInfo();
        setBackImg();
        getTitleTextView().setText("编辑队伍");
        ll_editeteam_carteam.setBackgroundColor(getResources().getColor(R.color.light_yellow));
    }

    @Override
    protected void initListener() {
        ll_editcar_teamphoto.setOnClickListener(this);
        ll_editcarteam_startadd.setOnClickListener(this);
        ll_editcarteam_endadd.setOnClickListener(this);
        tv_editcarteam_companyname.setOnClickListener(this);
        ll_editeteam_carteam.setOnClickListener(this);
        ll_editeteam_shipteam.setOnClickListener(this);
        submit.setOnClickListener(this);

    }

    private void reSetViewDta()
    {
        tv_editcarteam_teamname.setText("");
        lcFleet=null;
        tv_editcarteam_companyname.setText("");
        tv_editcarteam_phone.setText("");
        tv_editcarteam_startadd.setText("点击选择");
        tv_editcarteam_endadd.setText("点击选择");
        if(isCreateCarTeam)
        {
            submit.setText("提交/创建车队");
            tv_editcar_carshipphoto.setText("车队照片");
            ll_editeteam_carteam.setBackgroundColor(getResources().getColor(R.color.light_yellow));
            ll_editeteam_shipteam.setBackgroundColor(getResources().getColor(R.color.white));
        }
        else {
            submit.setText("提交/创建船队");
            tv_editcar_carshipphoto.setText("船队照片");
            ll_editeteam_carteam.setBackgroundColor(getResources().getColor(R.color.white));
            ll_editeteam_shipteam.setBackgroundColor(getResources().getColor(R.color.light_yellow));
        }

    }
    private void parseData() {
        fleetLines.clear();
        fleetLines.add(fleetLine);
        editCarTeamData.setFleetLeader(Integer.parseInt(SharedPrefUtil.getUserId()));
        editCarTeamData.setFleetName(tv_editcarteam_teamname.getText().toString().trim());
        editCarTeamData.setLeaderName(driverinfo.getUsername());
        editCarTeamData.setFleetState(2);
        editCarTeamData.setFleetPhone(tv_editcarteam_phone.getText().toString().trim());
        editCarTeamData.setLcFleet(lcFleet);
        editCarTeamData.setFleetImgs(fleetImgs);
        editCarTeamData.setFleetLines(fleetLines);
        if(isCreateCarTeam)
        {
            editCarTeamData.setFleetType(2);
        }
        else {
            editCarTeamData.setFleetType(3);

        }

    }

    private boolean checkAll() {
        if (TextUtils.isEmpty(tv_editcarteam_teamname.getText().toString())) {
            if (isCreateCarTeam) {
                PrintUtil.toast(activityContext,"车队名不能为空");
            }
            else {
                PrintUtil.toast(activityContext,"船队名不能为空");

            }
            return false;

        }
        if (tv_editcarteam_teamname.getText().toString().length() > 5 || tv_editcarteam_teamname.getText().toString().length() < 2) {
            PrintUtil.toast(activityContext,"请输入2—5个字的队名");
            return false;
        }
        if (lcFleet == null) {
            PrintUtil.toast(activityContext,"请填写所属公司");
            return false;
        }
        if (TextUtils.isEmpty(tv_editcarteam_phone.getText().toString().trim())) {
            PrintUtil.toast(activityContext,"请填写您的电话");
            return false;
        }
        if (fleetImgs.size() != 3) {
            if(isCreateCarTeam) {
                PrintUtil.toast(activityContext,"请上传三张车队照片");
            }
            else {
                PrintUtil.toast(activityContext,"请上传三张船队照片");

            }
            LogUtils.e("filepaths", fleetImgs.size() + "-----------");
            return false;
        }
        if (tv_editcarteam_startadd.getText().toString().equals("点击选择")) {
            PrintUtil.toast(activityContext,"请填写您常运路线的起点");
            return false;
        }
        if (tv_editcarteam_endadd.getText().toString().equals("点击选择")) {
            PrintUtil.toast(activityContext,"请填写您常运路线的终点");
            return false;
        }
        return true;
    }

    private void pickImage() {
        if (PermissoinUtil.checkAndRequestPermissions(activityContext,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE})){
            boolean showCamera = true;
            MultiImageSelector selector = MultiImageSelector.create(EditCarTeamActivity.this);
            selector.showCamera(showCamera);
            selector.count(maxNum);
            selector.multi();
            selector.origin(mSelectPath);
            selector.start(EditCarTeamActivity.this, REQUEST_IMAGE);

        }else {
            PrintUtil.toast(activityContext,"请给应用相应的权限");
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath.clear();
                mSelectPath.addAll(data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT));
                fillPhoto();
                if (mSelectPath.size() > 0) {
                    compressImages();
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_editeteam_carteam:
                if (!isCreateCarTeam){
                    isCreateCarTeam=true;
                    reSetViewDta();
                }
                break;
            case R.id.ll_editeteam_shipteam:
                if (isCreateCarTeam){
                    isCreateCarTeam=false;
                    reSetViewDta();
                }
                break;

            case R.id.ll_editcarteam_startadd:
                ActivityUtil.startActivity(activityContext,new Intent(activityContext,AddAddrActivity.class).putExtra("type",5));
                break;
            case R.id.ll_editcarteam_endadd:
                ActivityUtil.startActivity(activityContext,new Intent(activityContext,AddAddrActivity.class).putExtra("type",6));

                break;
            case R.id.ll_editcar_teamphoto://添加图片
                pickImage();
                break;
            case R.id.tv_editcarteam_companyname://添加物流公司
                ActivityUtil.startActivity(activityContext,TranslateCompanyActivity.class);
                break;

            case R.id.tv_act_editcarteam_submit:
                if (checkAll()) {
                    parseData();
                    createFleet();
                }
                break;
        }
    }



    //选取公司后
    public void onEventMainThread(SelectCompanyEvent event) {
        if (event.getData() != null) {
            LogisticsCompanyData logisticsCompanyData = event.getData();
            lcFleet = new LcFleet();
            lcFleet.setLogisticscompanyId(logisticsCompanyData.getLogisticsCompanyId());
            lcFleet.setCompanyGPSId(logisticsCompanyData.getCompanyGPSId());
            lcFleet.setState(3);
            tv_editcarteam_companyname.setText(logisticsCompanyData.getLogisticsCompanyName());
        }
    }
    //选取地址后
    public void onEventMainThread(AddAddrEvent event) {
        if (event.getEntity()!=null){
            LocationEntity entity=event.getEntity();
            PathEntity path=new PathEntity();
            path.setProvince(entity.getProvince());
            path.setCity(entity.getCity());
            path.setRegions(entity.getRegion_name());
            path.setAddress(entity.getBuilding());
            path.setDetailAddress(entity.getAddress());
            path.setLatAndLng(entity.getLatitude()+","+entity.getLongitude());
            if (event.getType()==5){
                path.setPointType("1");
                startPath=path;
                fleetLine.setStartCity(entity.getCity());
                fleetLine.setStartAddr(entity.getAddress());
                tv_editcarteam_startadd.setText(entity.getCity()+" "+entity.getAddress());
            }else if(event.getType()==6){
                 path.setPointType("2");
                 endPath=path;
                fleetLine.setTargetCity(entity.getCity());
                fleetLine.setTargetAddr(entity.getAddress());
                tv_editcarteam_endadd.setText(entity.getCity()+" "+entity.getAddress());
            }
        }
    }


    private void fillPhoto() {
        if (mSelectPath.size() > 0) {
            if (mSelectPath.size() == 1) {
                iv_editcarteam_icon1.setVisibility(View.VISIBLE);
                BitmapUtil.showLocalImg( mSelectPath.get(0),iv_editcarteam_icon1);
                iv_editcarteam_icon2.setVisibility(View.GONE);
                iv_editcarteam_icon3.setVisibility(View.GONE);
            } else if (mSelectPath.size() == 2) {
                iv_editcarteam_icon1.setVisibility(View.VISIBLE);
                BitmapUtil.showLocalImg( mSelectPath.get(0),iv_editcarteam_icon1);
                iv_editcarteam_icon2.setVisibility(View.VISIBLE);
                BitmapUtil.showLocalImg( mSelectPath.get(1),iv_editcarteam_icon2);
                iv_editcarteam_icon3.setVisibility(View.GONE);
            } else if (mSelectPath.size() == 3) {
                iv_editcarteam_icon1.setVisibility(View.VISIBLE);
                BitmapUtil.showLocalImg( mSelectPath.get(0),iv_editcarteam_icon1);
                iv_editcarteam_icon2.setVisibility(View.VISIBLE);
                BitmapUtil.showLocalImg( mSelectPath.get(1),iv_editcarteam_icon2);
                iv_editcarteam_icon3.setVisibility(View.VISIBLE);
                BitmapUtil.showLocalImg( mSelectPath.get(2),iv_editcarteam_icon3);
            }
        } else {
            iv_editcarteam_icon1.setVisibility(View.GONE);
            iv_editcarteam_icon2.setVisibility(View.GONE);
            iv_editcarteam_icon3.setVisibility(View.GONE);

        }
    }

    /**
     * 多图上传时压缩图片的方法
     */
    private void compressImages() {
        compressfiles.clear();
        fleetImgs.clear();
        for (String path : mSelectPath) {
            File photo = BitmapUtil.compressImage(path, this);
            compressfiles.add(photo);
        }
        uploadTeamIcons();
    }
    /**
     * 上传多图，多次上传单图
     */
    private void uploadTeamIcons() {
        for (File file : compressfiles) {
            uploadCarImage(file);
        }

    }

    /**
     * 上传单图
     *
     * @param file
     */
    private void uploadCarImage(final File file) {
        MyHttpUtil.uploadDriverImg(activityContext,file, new MyCallback<UpLoadImageResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(UpLoadImageResult result, int id) {
//
                if (result.getCode() == ConstUtil.OK && result.getData() != null) {
                    fleetImgs.add(result.getData());
                    file.delete();
                }
            }
        });
    }

    /**
     * 创建车队
     */
    private void createFleet() {
        DialogUtil.showLoadingDialog(activityContext,"创建车队...");
        MyHttpUtil.createFleet(activityContext,editCarTeamData, new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    PrintUtil.toast(activityContext,"创建成功");
                    BaseApplication.getInstance().getDriverInfoFromNet();//刷新数据
                    onBackPressed();
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });


    }

}
